import axios from 'axios'
import { baseURL, tokenKey } from './env'
import { Message, MessageBox } from 'element-ui'
import { getToken } from './mUtils'
import store from '@/store'
import Qs from 'qs'

// 创建axios
const service = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  responseType: 'json',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  transformRequest: [
    data => {
      return Qs.stringify(data)
    }
  ],
  withCredentials: false
})

// request请求拦截
service.interceptors.request.use(
  config => {
    if (getToken()) {
      // 让每个请求携带token-- [tokenKey]为自定义key 请根据实际情况自行修改
      config.header[tokenKey] = getToken()
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    // code为非200是抛错 可结合自己的业务修改
    const res = response.data
    console.log(res)
    if (res.code != 200 || res.code != '200') {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // 非法的token或者token过期
      if (
        res.code === 90002 ||
        res.code === '90002' ||
        res.code === 90003 ||
        res.code === '90003'
      ) {
        MessageBox.confirm(
          '你已被登出，可以取消继续留在该页面，或者重新登录!',
          '提示',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'info'
          }
        )
          .then(() => {
            store.dispatch('FedlogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
          .catch(e => {
            console.log(e)
          })
      }
      if (res.code === '400' || res.code === 400) {
        MessageBox.confirm('用户名不存在!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
          .then(() => {
            store.dispatch('FedlogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
          .catch(e => {
            console.log(e)
          })
      }
      if (res.code === 401 || res.code === '401') {
        MessageBox.confirm('密码错误!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
          .then(() => {
            store.dispatch('FedlogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
          .catch(e => {
            console.log(e)
          })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
